import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Dimensions, Text, Image, TouchableOpacity } from "react-native";
import { Icon, Button, Tab, TabView } from "@rneui/themed";
import { useIsFocused } from '@react-navigation/native';
import { Shadow } from 'react-native-shadow-2';
import "@ethersproject/shims";
import { ethers } from 'ethers';
import { useSelector, useDispatch } from "react-redux";
import { PayWithArray } from '@/config/config'
import CoinNoSelectedImg from '@/assets/safe/coin.png'
import CoinSelectedImg from '@/assets/safe/coin_selected.png'
import ScanImg from '@/assets/safe/scan.png'
import CommonContext from '@/utils/createContext'
import AddressModal from '@/components/AddressModal'
import SafeReader from './components/SafeReader'
import AssetList from './components/AssetList'
import CollectionList from './components/CollectionList'
import Loading from "@/components/LoadingModal";
import api from '@/request/api';
import { getValue } from '@/utils/deviceStorage';

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const SectokenMain = (props) => {

    const isFocused = useIsFocused()
    const [number, setNumber] = useState(0);
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [tabIndex, setTabIndex] = useState(0);
    const [modalVisible, setModalVisible] = useState(false);
    const [addressVisible, setAddressVisible] = useState(false);
    const [safeCollectList, setSafeCollectList] = useState([]);
    const dispatch = useDispatch();
    const selectedSafeWallet = useSelector((state) => state.sectokenMainReducer.selectedSafeWallet);
    const safeAssetList = useSelector((state) => state.sectokenMainReducer.safeAssetList);
    const readOnly = useSelector((state) => state.sectokenMainReducer.readOnly);

    useEffect(() => {
        let params = props.route.params
        if (params && params.source === 'create-safe') {
            setModalVisible(true)
        } else {
            init()
        }
    }, [props, isFocused])

    const init = () => {
        if (isFocused && selectedSafeWallet && selectedSafeWallet.address) {
            getPageData()
        }
        let wallet = getValue('selectedWallet')
        let addressList = selectedSafeWallet?.ownerList
        let label = true
        addressList && addressList.forEach(item => {
            if (item.address?.toLowerCase() === wallet.address?.toLowerCase()) {
                dispatch({ type: "setReadOnly", value: false })
                label = false
            }
        });
        if (label) {
            dispatch({ type: "setReadOnly", value: true })
        }
    }

    const getPageData = () => {
        setLoadingVisible(true)
        setTimeout(async () => {
            let res1 = await api.get_safe_balance_eth(selectedSafeWallet.address)
            let arr1 = res1.items
            if (arr1 && arr1.length > 0) {
                for (let i = 0; i < arr1.length; i++) {
                    let amount = ethers.utils.formatUnits(arr1[i].balance, arr1[i].tokenInfo.decimals)
                    arr1[i].balance = amount
                    let str = arr1[i].tokenInfo.logoUri
                    if (str.indexOf('/media/https%3A') != -1) {
                        str = str.replace('/media/https%3A', 'https:/')
                        arr1[i].tokenInfo.logoUri = str
                    }
                }
            }
            dispatch({ type: "setSafeAssetList", value: arr1 })
            let res2 = await api.get_safe_balance_erc721(selectedSafeWallet.address)
            let arr2 = res2
            if (arr2 && arr2.length > 0) {
                for (let i = 0; i < arr2.length; i++) {
                    let str = arr2[i].logoUri
                    if (str.indexOf('/media/https%3A') != -1) {
                        str = str.replace('/media/https%3A', 'https:/')
                        arr2[i].logoUri = str
                    }
                }
            }
            setSafeCollectList(arr2)
            let res3 = await api.get_safe_queue(selectedSafeWallet.address)
            setNumber(res3 && res3.results && res3.results.length)
            setLoadingVisible(false)
        }, 100);
    }

    const handlePressLogo = () => {
        props.navigation.navigate('safe-account-setting')
    }

    const handlePressAccount = () => {
        props.navigation.navigate('safe-account-change')
    }

    const handlePressSend = () => {
        if (!readOnly) {
            props.navigation.navigate('safe-send-asset')
        }
    }

    const handlePressReceive = () => {
        if (!readOnly) {
            setAddressVisible(true)
        }
    }

    const handlePressTransactions = () => {
        props.navigation.navigate('safe-transcation')
    }

    const handlePressAdd = () => {
        if (!readOnly) { }
    }

    const handlePressItem = (item) => {
        if (!readOnly) {
            dispatch({ type: "setSelectedSafeAsset", value: item || {} })
            props.navigation.navigate('safe-send-info')
        }
    }

    const handlePressScan = async () => {
    }

    const handleColse = () => {
        setModalVisible(false)
        init()
    }

    return (
        <View style={styles.container}>
            <View style={styles.header}>
                <View style={styles.header_left}>
                    <TouchableOpacity onPress={handlePressLogo}>
                        <Image source={PayWithArray[selectedSafeWallet.profileImg]} style={{ ...styles.img1, marginLeft: 15 * ratio }} />
                    </TouchableOpacity>
                    <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }} onPress={handlePressAccount}>
                        <Text style={{ ...styles.title1, marginLeft: 10 * ratio, color: '#2C2C2C' }}>{selectedSafeWallet.label}</Text>
                        {readOnly && <Text style={{ ...styles.title2, marginLeft: 10 * ratio, color: '#8E8E8E' }}>Read-only</Text>}
                        <Icon style={{ marginLeft: 5 * ratio }} type='antdesign' name='caretright' color='#000000' size={9} />
                    </TouchableOpacity>
                </View>
                <TouchableOpacity style={styles.header_right} onPress={handlePressScan}>
                    <Image source={ScanImg} style={{ ...styles.img2, marginRight: 15 * ratio }} />
                </TouchableOpacity>
            </View>
            <Shadow offset={[0, 2]}
                distance={0} startColor='rgba(99, 99, 99,0.06)' finalColor='transparent' radius={3.84}>
                <View style={styles.divider}></View>
            </Shadow>
            <View style={{ justifyContent: 'center', alignItems: 'center', marginTop: 31 * ratio }}>
                <View style={{
                    width: 126 * ratio, height: 30 * ratio, justifyContent: 'center',
                    alignItems: 'center', backgroundColor: '#E6F2FD', borderRadius: 15
                }}>
                    <Text
                        ellipsizeMode='middle'
                        numberOfLines={1}
                        style={{ ...styles.title2, width: 85 * ratio, color: '#484C4F' }}>
                        {selectedSafeWallet.address}
                    </Text>
                </View>
            </View>
            <View style={{ flexDirection: 'row', justifyContent: 'center', marginTop: 33 * ratio }}>
                <Button onPress={handlePressSend}
                    buttonStyle={{ ...styles.button, backgroundColor: '#0A6EEB', marginRight: 10 * ratio }} >
                    <Icon type='feather' name="arrow-up-right" color="#FFFFFF" size={14} />
                    <Text style={{ ...styles.title1, color: '#FFFFFF', marginLeft: 8 * ratio }}>Send</Text>
                </Button>
                <TouchableOpacity onPress={handlePressReceive}
                    style={{ ...styles.button, backgroundColor: '#FFFFFF', opacity: 0.5, borderColor: '#006AEF', borderWidth: 1 }} >
                    <Icon type='feather' name="arrow-down-left" color="#0A6EEB" size={14} />
                    <Text style={{ ...styles.title1, color: '#0A6EEB', marginLeft: 8 * ratio }}>Receive</Text>
                </TouchableOpacity>
            </View>
            <TouchableOpacity style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop: 22 * ratio }}
                onPress={handlePressTransactions}>
                <Text style={{ ...styles.title3, marginLeft: 15 * ratio }}>Transactions</Text>
                <View style={{ flexDirection: 'row', alignItems: 'center' }} >
                    <Text style={{ ...styles.title4, color: '#9A9A9A', margin: 11 * ratio }}>{number}</Text>
                    <Icon style={{ marginRight: 15 * ratio }} type='antdesign' name="right" color="#717171" size={10} />
                </View>
            </TouchableOpacity>
            <View style={{ flex: 1 }}>
                <Tab value={tabIndex} onChange={(e) => setTabIndex(e)} indicatorStyle={{ backgroundColor: '#5757F9' }}>
                    <Tab.Item
                        containerStyle={{ backgroundColor: '#F7F7F7' }}
                        title={<View style={{ flexDirection: 'row', alignItems: 'center', height: 45 * ratio }}>
                            {tabIndex == 0 ? <Image source={CoinSelectedImg} style={styles.img3} /> : <Image source={CoinNoSelectedImg} style={styles.img3} />}
                            <Text style={{ ...styles.title2, color: tabIndex == 0 ? '#0A6EEB' : '#BCBCBC', marginLeft: 4 * ratio }}>COINS</Text>
                        </View>}>
                    </Tab.Item>
                    <Tab.Item
                        containerStyle={{ backgroundColor: '#F7F7F7' }}
                        title={<View style={{ flexDirection: 'row', alignItems: 'center', height: 45 * ratio }}>
                            <Icon name='staro' size={14} type='antdesign' color={tabIndex == 1 ? '#0A6EEB' : '#BCBCBC'} />
                            <Text style={{ ...styles.title2, color: tabIndex == 1 ? '#0A6EEB' : '#BCBCBC', marginLeft: 4 * ratio }}>COLLECTIBLES</Text>
                        </View>}>
                    </Tab.Item>
                </Tab>
                <TabView value={tabIndex} onChange={(e) => setTabIndex(e)} animationType="spring">
                    <TabView.Item>
                        <CommonContext.Provider value={{ safeAssetList, handlePressItem }}>
                            <AssetList />
                        </CommonContext.Provider>
                    </TabView.Item>
                    <TabView.Item>
                        <CommonContext.Provider value={{ safeCollectList, handlePressAdd }}>
                            <CollectionList />
                        </CommonContext.Provider>
                    </TabView.Item>
                </TabView>
            </View>
            <CommonContext.Provider value={{ modalVisible, handleColse }}>
                <SafeReader />
            </CommonContext.Provider>
            <CommonContext.Provider value={{ modalVisible: addressVisible, setModalVisible: setAddressVisible, selectedSafeWallet }}>
                <AddressModal />
            </CommonContext.Provider>
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FFFFFF'
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginTop: 30 * ratio,
        marginBottom: 10 * ratio
    },
    header_left: {
        flex: 8,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center'
    },
    header_right: {
        flex: 2,
        justifyContent: 'flex-end',
        alignItems: 'center'
    },
    title1: {
        fontSize: 16,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        lineHeight: 24
    },
    title3: {
        fontSize: 14,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        lineHeight: 20
    },
    title2: {
        fontSize: 12,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        lineHeight: 18
    },
    title4: {
        fontSize: 12,
        fontFamily: 'SourceHanSansCN-Regular, SourceHanSansCN',
        fontWeight: '400',
        lineHeight: 18
    },
    divider: {
        width: width,
        height: 18 * ratio,
        backgroundColor: '#F7F7F7',
        marginTop: 10
    },
    button: {
        width: 134 * ratio,
        height: 38 * ratio,
        borderRadius: 11,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
    img1: {
        width: 30 * ratio,
        height: 30 * ratio
    },
    img2: {
        width: 19 * ratio,
        height: 18 * ratio
    },
    img3: {
        width: 14 * ratio,
        height: 13 * ratio
    }
})
export default SectokenMain